//
//	 ______    ______    ______    
//	/\  __ \  /\  ___\  /\  ___\   
//	\ \  __<  \ \  __\_ \ \  __\_ 
//	 \ \_____\ \ \_____\ \ \_____\ 
//	  \/_____/  \/_____/  \/_____/ 
//
//	Powered by BeeFramework
//
//
//  LoginBoard.m
//  iHeima
//
//  Created by he chao on 5/22/14.
//  Copyright (c) 2014 leon. All rights reserved.
//

#import "LoginBoard.h"
#import "MainBoard.h"
#import "CompleteUserInfoBoard.h"
#import "SignupBoard.h"
#import "ForgetPasswordBoard.h"
#import "GuideBoard.h"
#import "ActivitiesBoard.h"


#pragma mark -

@interface LoginBoard()<UITextViewDelegate,UITextFieldDelegate>
{
	//<#@private var#>
    
    BOOL _keyBoardIsShown;
    
    UIView* _bgView;
    
    NSArray* _filed;
    
    BOOL _isShouldMove;
    
}
@end

@implementation LoginBoard
//DEF_SINGLETON(LoginBoard)

DEF_SIGNAL(LOGIN)
DEF_SIGNAL(SIGNUP)
DEF_SIGNAL(FORGET)

- (void)load
{
}

- (void)unload
{
}

#pragma mark - Signal

ON_CREATE_VIEWS( signal )
{
    //[self setNeedsStatusBarAppearanceUpdate];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self loadContent];
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"isFirstEnter"] boolValue]) {
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"hasLogin"] boolValue]) {
            MainBoard *board = [MainBoard sharedInstance];
            
            
            
            [self.stack pushBoard:board animated:NO];
            
            NSLog(@"是否第一次登陆:%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"isFirstEnter"]);
            
            printf("----登陆");
            
        }
    }
    else {
        GuideBoard *board = [[GuideBoard alloc] init];
        [self.stack pushBoard:board animated:NO];
    }
    
    
}

ON_DELETE_VIEWS( signal )
{
}

ON_LAYOUT_VIEWS( signal )
{
}

ON_WILL_APPEAR( signal )
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    //[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
}

ON_DID_APPEAR( signal )
{
}

ON_WILL_DISAPPEAR( signal )
{
}

ON_DID_DISAPPEAR( signal )
{
}

ON_SIGNAL3( BeeUINavigationBar, LEFT_TOUCHED, signal )
{
}

ON_SIGNAL3( BeeUINavigationBar, RIGHT_TOUCHED, signal )
{
}

//ON_SIGNAL2(BeeUITextField, signal) {
//    if ([signal is:BeeUITextField.RETURN]) {
//        if (signal.source == field[0]) {
//            [field[1] becomeFirstResponder];
//        }
//        else {
//            [field[1] resignFirstResponder];
//           // [self sendUISignal:LoginBoard.LOGIN];
//            [self hiddenKeyboard];
//            
//        }
//    }
//}

ON_SIGNAL2(LoginBoard, signal){
    if ([signal is:LoginBoard.LOGIN]) {
        [self POST:[NSString stringWithFormat:@"%@/apiuser/login",kBaseUrl]].PARAM(@"username",field[0].text).PARAM(@"password",field[1].text).PARAM(@"uuid",[BeeSystemInfo deviceUUID]).PARAM(@"version",@"1.0");
        NSLog(@"点击登录");
        
       
        
//        MainBoard *board = [MainBoard sharedInstance];
//        [self.stack pushBoard:board animated:YES];
    }
    else if ([signal is:LoginBoard.SIGNUP]) {
        SignupBoard *board = [[SignupBoard alloc] init];
        [self.stack pushBoard:board animated:YES];
//        CompleteUserInfoBoard *board = [[CompleteUserInfoBoard alloc] init];
//        [self.stack pushBoard:board animated:YES];
    }
    else if ([signal is:LoginBoard.FORGET]) {
        ForgetPasswordBoard *board = [[ForgetPasswordBoard alloc] init];
        [self.stack pushBoard:board animated:YES];
    }
}

- (void)handleRequest:(BeeRequest *)request
{
    if(request.failed)
    {
        [[BeeUITipsCenter sharedInstance] dismissTips];
        NETWORK_ERROR
    }
    else if (request.succeed)
    {
        id json = [request.responseString mutableObjectFromJSONString];
        
        NSLog(@"登录返回的JSON：%@",json);
        
        
        switch ([json[@"status"] intValue]) {
            case 1:
            {
                
                NSLog(@"当前登陆成功");
                
                [[NSUserDefaults standardUserDefaults] setObject:[json[@"res"] JSONString] forKey:@"userInfo"];
                [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasLogin"];
                MainBoard *board = [MainBoard sharedInstance];
                
                
                [self.stack pushBoard:board animated:YES];
            }
                break;
            case 0:
            {
                [[BeeUITipsCenter sharedInstance] presentMessageTips:json[@"info"]];
                [[BeeUITipsCenter sharedInstance] presentMessageTips:@"账号或密码有误，请重新输入"];
                
                
    
                
            }
                break;
                
            default:
                break;
        }
    }
}


//-(UIStatusBarStyle)preferredStatusBarStyle{
//    return UIStatusBarStyleBlackTranslucent;
//}







- (void) registerForKeyboardNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil];
    
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardWillHideNotification object:nil];
    
}

- (void) keyboardWasShown:(NSNotification *) notif{

    if (_isShouldMove) {
        //change UI frame
        NSTimeInterval animationDuration=0.30f;
        [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
        [UIView setAnimationDuration:animationDuration];
        float width = self.view.frame.size.width;
        float height = self.view.frame.size.height;
       
        CGRect rect=CGRectMake(0.0f,-60,width,height);
        //self.view.frame=rect;
        _bgView.frame = rect;
        [UIView commitAnimations];
       
        
    }
    _isShouldMove = NO;
    
    
}


- (void)resumeBg{
    
    NSTimeInterval animationDuration=0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    float width = self.view.frame.size.width;
    float height = self.view.frame.size.height;
    
    CGRect rect=CGRectMake(0.0f,0.0f,width,height);
    //self.view.frame=rect;
    _bgView.frame = rect;
    [UIView commitAnimations];
    
    
    
}

- (void)hiddenKeyboard{
    
    
    [field[0] resignFirstResponder];
    
    [field[1] resignFirstResponder];
    
    
    [self resumeBg];
    _isShouldMove = YES;
    
    
}

- (void)nextOnKeyboard:(BeeUITextField*)sender{
   
    if (sender == field[0]) {
        
       
        [field[1] becomeFirstResponder];
        
        
    }else if (sender == field[1]){
        [self hiddenKeyboard];
    }
    
}


- (void)loadContent{
    
    _isShouldMove = YES;
    _bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 568)];
    UITapGestureRecognizer* tapAction = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenKeyboard)];
    [_bgView addGestureRecognizer:tapAction];
    
    [_bgView setUserInteractionEnabled:YES];
    [_bgView setBackgroundColor:[UIColor clearColor]];
    [self registerForKeyboardNotifications];
    
    self.view.backgroundImage = IMAGESTRING(@"background");
    
    BeeUIImageView *imgIcon = [BeeUIImageView spawn];
    imgIcon.frame = CGRectMake(0, 0, 91, 128);
    imgIcon.image = IMAGESTRING(@"login_icon");
    imgIcon.center = CGPointMake(self.viewWidth/2.0, 128);
    //[self.view addSubview:imgIcon];
    [_bgView addSubview:imgIcon];
    
    
    for (int i = 0; i < 2; i++) {
        BeeUIImageView *line = [BeeUIImageView spawn];
        line.frame = CGRectMake(36, 270+55*i, 228, 2);
        line.contentMode = UIViewContentModeScaleToFill;
        line.image = IMAGESTRING(@"line");
        //[self.view addSubview:line];
        [_bgView addSubview:line];
        
        BeeUIImageView *imgIcon = [BeeUIImageView spawn];
        imgIcon.frame = CGRectMake(0, 0, 42, 42);
        imgIcon.image = i==0?IMAGESTRING(@"login_icon1"):IMAGESTRING(@"login_icon2");
        
        field[i] = [BeeUITextField spawn];
        field[i].frame = CGRectMake(line.left, line.bottom-42, line.width, 42);
        //[self.view addSubview:field[i]];
        [_bgView addSubview:field[i]];
        
        field[i].leftViewMode = UITextFieldViewModeAlways;
        field[i].leftView = imgIcon;
        field[i].placeholder = i==0?@"手机号码":@"密码";
        field[i].clearButtonMode = UITextFieldViewModeWhileEditing;
        if (field==0) {
            field[i].returnKeyType = UIReturnKeyNext;
        }
        else {
            field[i].returnKeyType = UIReturnKeyDone;
            field[1].secureTextEntry = YES;
        }
    }
//    field[0].text = @"";
//    field[1].text = @"123456";
    
  
    
    field[1].delegate = self;
    
    [field[0] addTarget:self action:@selector(nextOnKeyboard:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [field[1] addTarget:self action:@selector(nextOnKeyboard:) forControlEvents:UIControlEventEditingDidEndOnExit];
    
    
    BaseButton *btnLogin = [BaseButton initBaseBtn:IMAGESTRING(@"btn1") highlight:IMAGESTRING(@"btn1_pre") text:@"登录" textColor:[UIColor whiteColor] font:FONT(14)];
    btnLogin.frame = CGRectMake(field[0].left, field[1].bottom+34, 228, 42);
    [btnLogin addSignal:LoginBoard.LOGIN forControlEvents:UIControlEventTouchUpInside];
   // [self.view addSubview:btnLogin];
    
    [_bgView addSubview:btnLogin];
    
//    BeeUIButton *btnForget = [BeeUIButton spawn];
//    btnForget.frame  = CGRectMake(0, self.viewHeight-40, self.viewWidth, 40);
//    [btnForget setBackgroundColor:[UIColor whiteColor]];
//    [btnForget addSignal:LoginBoard.FORGET forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:btnForget];
    
    BeeUILabel *lb = [BeeUILabel spawn];
    lb.frame = CGRectMake(0, btnLogin.bottom, self.viewWidth, 40);
    lb.font = FONT(14);
    lb.textColor = RGB(123, 123, 123);
    lb.text = @"忘记密码";
    [lb makeTappable:LoginBoard.FORGET];
    //[self.view addSubview:lb];
     [_bgView addSubview:lb];
    
    BeeUILabel *lbSignup = [BeeUILabel spawn];
    lbSignup.frame = CGRectMake(self.viewWidth-70, self.viewHeight-40, 80, 40);
    lbSignup.textColor = RGB(18, 125, 242);
    lbSignup.text = @"注册";
    lbSignup.font = FONT(16);
    [lbSignup makeTappable:LoginBoard.SIGNUP];
    //[self.view addSubview:lbSignup];
    [_bgView addSubview:lbSignup];
   
    [self.view addSubview:_bgView];
    
}
- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
}

@end
